package org.douxiaoban.client.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import com.mobclick.android.MobclickAgent;

import org.douxiaoban.client.R;
import org.douxiaoban.client.util.WorkspaceView;
import org.douxiaoban.client.util.WorkspaceView.ScrollToScreenCallback;
import org.douxiaoban.client.adapter.MailAdapter;
import org.douxiaoban.client.adapter.MiniBlogAdapter;
import org.douxiaoban.client.api.DoubanList;
import org.douxiaoban.client.api.DoubanListType;
import org.douxiaoban.client.api.MailData;
import org.douxiaoban.client.api.MailList;
import org.douxiaoban.client.api.MiniBlogItemData;
import org.douxiaoban.client.app.App;
import org.douxiaoban.client.app.Assistant;
import org.douxiaoban.client.util.ThreadTool;
import org.douxiaoban.client.widget.PopupRecommend;
import org.douxiaoban.client.widget.TitleStyle;

import java.util.ArrayList;
import java.util.List;

public class MailActivity extends Activity implements ScrollToScreenCallback{
	private WorkspaceView mailWorkspace;
	MailList mInbox;
	MailList mOutbox;
	private MailHandler mHandler;
	
	
	private final static int REP_MAIL = 0;
	private final static int DEL_MAIL = 1;
	
	private TitleStyle mTitle;
	
	private ThreadTool mThread;
	
	private int mCurrentIndex;
	private boolean mCurrentBox;
	
	//更多
	private TextView mRefresh;
	private ProgressBar mProgressHead;
	
	private PopupRecommend mPopup;
	
	
	public void onCreate(Bundle bundle){
		super.onCreate(bundle);		
		//setContentView(R.layout.mail_home);
		mailWorkspace = new WorkspaceView(this, null);
	     requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
	     setContentView(mailWorkspace);
	     getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.custom_title);

        mTitle = new TitleStyle(this);
        mTitle.initTitleStyle();
        mTitle.initPageController(2,1);
        mTitle.setTitle(getString(R.string.titleMailInbox));
        
        LayoutInflater inflater = LayoutInflater.from(this);
	    View headView = inflater.inflate(R.layout.head_view, null);
	    mRefresh = (TextView)headView.findViewById(R.id.headViewRefresh);
	    mProgressHead = (ProgressBar)headView.findViewById(R.id.headViewProgress);
		
		//(WorkspaceView)findViewById(R.id.mailWorkspace);
		mailWorkspace.setScrollToScreenCallback(this);
		
		mHandler = new MailHandler();
					
//		LayoutInflater flater = LayoutInflater.from(this);
//		View viewInbox = flater.inflate(R.layout.list, null);
//		View viewOutbox = flater.inflate(R.layout.list, null);
		
		MailAdapter inboxAdapter = new MailAdapter(this);
		MailAdapter outboxAdapter = new MailAdapter(this);
		mInbox = new MailList(this, inboxAdapter, DoubanListType.MAIL_INBOX);
		mOutbox = new MailList(this, outboxAdapter, DoubanListType.MAIL_OUTBOX);
		
		mInbox.getListView().addHeaderView(headView);
		mOutbox.getListView().addHeaderView(headView);
		
		mInbox.getListView().setAdapter(inboxAdapter);
		mOutbox.getListView().setAdapter(outboxAdapter);
		
		mailWorkspace.addView(mInbox.getMainview());
		mailWorkspace.addView(mOutbox.getMainview());
		
		initListener(mInbox);
		initListener(mOutbox);
		
		mThread = ThreadTool.instace(this);
		refresh(mInbox);
		
		mPopup = new PopupRecommend(this);
		
	}
	
	private class MailHandler extends Handler {
		@Override
		public void handleMessage(Message msg){
			Bundle bundle = msg.getData();
			ThreadTool.MailListSerialz serialz;
			switch(msg.what){
			case Assistant.TOOLS_MSG_INBOX:
				serialz = (ThreadTool.MailListSerialz)bundle.getSerializable(Assistant.TOOLS_KEY_INBOX);
				if(null != serialz.mList){
					updateMailList(mInbox, serialz.mList);
				}else{
					//提示网络异常
					mPopup.showToastWindow(Assistant.FAIL_POP, "网络异常");
				}
				break;
			case Assistant.TOOLS_MSG_OUTBOX:
				serialz = (ThreadTool.MailListSerialz)bundle.getSerializable(Assistant.TOOLS_KEY_OUTBOX);
				if(null != serialz.mList){
					updateMailList(mOutbox, serialz.mList);
				}else{
					//提示网络异常
					mPopup.showToastWindow(Assistant.FAIL_POP, "网络异常");
				}
				break;
			case Assistant.TOOLS_MSG_INBOX_RE:
				serialz = (ThreadTool.MailListSerialz)bundle.getSerializable(Assistant.TOOLS_KEY_INBOX);
				if(null != serialz.mList){
					insertNewData(mInbox, serialz.mList);
				}else{
					//提示网络异常
					refreshFail();
				}
				break;
			case Assistant.TOOLS_MSG_OUTBOX_RE:
				serialz = (ThreadTool.MailListSerialz)bundle.getSerializable(Assistant.TOOLS_KEY_OUTBOX);
				if(null != serialz.mList){
					insertNewData(mOutbox, serialz.mList);
				}else{
					//提示网络异常
					refreshFail();
				}
				break;
			case Assistant.TOOLS_MSG_ONE_MAIL:
				//
				break;
				
			case Assistant.MSG_DEL_MAIL:
				if(bundle.getBoolean(Assistant.KEY_SUCCESS)){
					//提示删除成功					
					int index = bundle.getInt(Assistant.KEY_MAIL_INDEX);
					removeOneMail(index, bundle.getBoolean(Assistant.KEY_IS_INBOX));
					mPopup.showToastWindow(Assistant.SUCCESS_POP, "成功删除豆邮");
				}else{
					//删除不成功
					mPopup.showToastWindow(Assistant.FAIL_POP, "删除豆邮失败");
				}
			default:
				break;
			}
		}
	}
	
	private void initListener(final MailList mailList){
		//final MailAdapter adapter = mailList.getAdapter();
		mailList.getListView().setOnItemClickListener(new OnItemClickListener(){
			//短按跳到邮件详情
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int index,
					long id) {
				if(0 == index--){
					refresh(mailList);
					return;
				}
				MailData mailData = (MailData)mailList.getAdapter().getItem(index);
				toMailInfo(mailData, index);	
			}
		});
		//长按弹出回复和删除
		mailList.getListView().setOnItemLongClickListener(new OnItemLongClickListener(){	
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int index, long arg3) {
				if(0 == index--){
					return false;
				}
				final MailData mailData = (MailData)mailList.getAdapter().getItem(index);
				final int listIndex = index;
				DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface arg0, int posDlg) {
						// TODO Auto-generated method stub
						//clickItem(posList, posDlg);
						sendIntent(mailData, posDlg, listIndex);
						
					}
					
				};
				String [] listStr = new String[]{"回应","删除"};
				new AlertDialog.Builder(MailActivity.this)
				.setTitle("操作菜单")
				.setItems(listStr, listener).show();
				return false;
			}
		});

		mailList.getListView().setOnScrollListener(new OnScrollListener(){

			@Override
			public void onScroll(AbsListView v, int firstVisbleItem, int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				if(firstVisbleItem + visibleItemCount == totalItemCount 
					&& !mailList.getIsUpdateing() 
					&& !mailList.getIsEnd()){	
					mailList.setIsUpdateing(true);
					getMore(mailList);
				}
			}

			@Override
			public void onScrollStateChanged(AbsListView arg0, int arg1) {
				// TODO Auto-generated method stub
				
			}
			
		});
		
	}
	
	private void sendIntent(MailData data,  int posDlg, int listIndex){
		if(REP_MAIL == posDlg){
			//回应豆油
			toRepMail(data);
			
		}else if(DEL_MAIL == posDlg){
			// 删除豆油
			mThread.delMail(mHandler, String.valueOf(data.mId), data.mIsInbox, listIndex); 
		}
	}
	
	private void toRepMail(MailData mailData){
		Intent intent = new Intent();
		Bundle bundle = new Bundle();
		String userId = mailData.mIsInbox ? mailData.mSenderId : mailData.mRecName;
		bundle.putString(Assistant.KEY_MAIL_ID, userId);
		String name = mailData.mIsInbox ? mailData.mSenderName : mailData.mRecName;
		bundle.putString(Assistant.KEY_USER_NAME, name);
		intent.putExtras(bundle);
		intent.setClass(MailActivity.this, SendMailActivity.class);
		startActivity(intent);
	}
	
	private void toMailInfo(MailData mailData, int index){
		Intent intent = new Intent();
		Bundle bundle = new Bundle();
		bundle.putString(Assistant.KEY_MAIL_ID, String.valueOf(mailData.mId));
		bundle.putBoolean(Assistant.KEY_IS_INBOX, mailData.mIsInbox);
		intent.putExtras(bundle);
		intent.setClass(MailActivity.this, OneMailInfoActivity.class);
		mCurrentIndex = index;
		mCurrentBox = mailData.mIsInbox;
		mailData.mUnread = false;
		setToRead();
		startActivityForResult(intent, Assistant.DEL_MAIL_SUCCESS);
	}
	
	//当在邮件详情下点击删除按钮！
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data){
		super.onActivityResult(requestCode, resultCode, data);
		if(Assistant.DEL_MAIL_SUCCESS == resultCode){
			removeOneMail(mCurrentIndex, mCurrentBox);
			mPopup.showToastWindow(Assistant.SUCCESS_POP, "成功删除豆邮");
		}else if(Assistant.DEL_MAIL_UN_SUCCESS == resultCode){
			mPopup.showToastWindow(Assistant.FAIL_POP, "删除豆邮失败");
		}
	}
	
	/**
	 * 获取更多
	 * @param mailList 指定的列表，收件箱还是发件箱
	 */
	private void getMore(DoubanList mailList){
		int start  = mailList.getCount() + 1;
		DoubanListType type = mailList.getType();
		mThread.getMailList(mHandler, start, App.mMailMax, type);
	}
	/**
	 * 刷新操作
	 * @param mailList
	 */
	private void refresh(DoubanList mailList){
		mRefresh.setText("获取数据");
		mProgressHead.setVisibility(View.VISIBLE);
		
		int start = 1;
		DoubanListType type = mailList.getType();
		mThread.getMailListRe(mHandler, start, App.mMailMax, type);
	}
	
	//更新更多
	public void updateMailList(DoubanList mailList, ArrayList<MailData> itemData){	
		
		if(0 == itemData.size()){
			Log.v("updateMiniBlog::itemData size", String.valueOf(itemData.size()));
			mailList.setIsEnd(true);
			return;
		}
		mailList.setIsUpdateing(false);
		int start = getOldIndex(itemData, mailList.getLastId());
		if(-1 == start){
			mailList.setCount(mailList.getCount() + App.max);
			mailList.setIsUpdateing(true);
			getMore(mailList);
			return;
		}
		//悲剧的api..不知道神马时候能更新
		mailList.setCount(mailList.getCount() + itemData.size() - start);
		
		List<MailData> sub = itemData.subList(start, itemData.size());
		itemData = new ArrayList<MailData>(sub);	
		((MailAdapter)mailList.getAdapter()).addDataTail(itemData);

		mailList.setIsFirst(false);
		
		//更新最后一个id
		int lastIndex = mailList.getAdapter().getCount() - 1;
		MailData item = (MailData)((MailAdapter)mailList.getAdapter()).getItem(lastIndex);
		mailList.setLastId(item.mId);
	}
	
	
	
	/**
	 * 更新刷新操作,要对插入位置做分析
	 * 
	 * @param list 获取到的新数据
	 */
	private void insertNewData(DoubanList mailList, ArrayList<MailData> itemData){
		mProgressHead.setVisibility(View.GONE);
		mRefresh.setText("刷新");
		
		mailList.getProgressBar().setVisibility(View.GONE);
		mailList.getListView().setVisibility(View.VISIBLE);
		
		int index = getNewIndex(itemData, mailList.getFirstId());
		if(-1 == index){
			return;
		}
		List<MailData> sub = itemData.subList(0, index);
		itemData = new ArrayList<MailData>(sub);

		MailAdapter adapter = (MailAdapter)mailList.getAdapter();
		adapter.addDataPre(itemData);
		if(mailList.getIsFirst()){
			updateLastId(mailList);
			mailList.setIsFirst(false);
			mailList.setCount(mailList.getCount() + itemData.size());
		}
		updateFirstId(mailList);
		//补偿留给addmore
		//this.setCount(this.getCount() + index);
		mailList.setIsUpdateing(false);
	}
		
	//更新firstID  
	private void updateFirstId(DoubanList list){
		int id = ((MailAdapter)list.getAdapter()).getFirstId();
		list.setFirstId(id);
	}
	
	//更新lastID
	private void updateLastId(DoubanList list){
		int id = ((MailAdapter)list.getAdapter()).getLastId();
		list.setLastId(id);
	}
	
	//刷新操作的位置分析
	private int getNewIndex(ArrayList<MailData> list,int id){
		for(int index = list.size()-1; index >=0 ; index--){
			if(list.get(index).mId > id){
				//作为右边界
				return index + 1;
			}			
		}
		return -1;
	}
	
	/**
	 * 获取更多时候的位置分析
	 * @param list 获取到的数据
	 * @param id   当前最后一个item的id值
	 * @return
	 */
	private int getOldIndex(ArrayList<MailData> list,int id){
		for(int index = 0; index != list.size(); index++){
			if(list.get(index).mId < id){
				return index;
			}			
		}
		return -1;
	}
	
//	private void updateMailList(MailList list, ArrayList<MailData> mailData){
//		list.getProgressBar().setVisibility(View.GONE);
//		list.getListView().setVisibility(View.VISIBLE);
//		((MailAdapter)list.getAdapter()).addDataToTail(mailData);
//		if(mailData.size() < App.mMailMax){
//			list.setIsEnd(true);
//		}
//		list.setIsUpdateing(false);
//		list.setIsFirst(false);
//	}
	
	public void callback(int index){
		if(1 == index){
			mTitle.setCurrentPage(index+1);
			mTitle.setTitle(getString(R.string.titleMailOutbox));
			if(mOutbox.getIsFirst()){
				mThread.getMailListRe(mHandler, 1, App.mMailMax, DoubanListType.MAIL_OUTBOX);
			}
		}else if(0 == index){
			mTitle.setCurrentPage(index+1);
			mTitle.setTitle(getString(R.string.titleMailInbox));
		}
	}
	/**
	 * 在ui上删除某封邮件
	 * @param mailIndex 要删除的邮件的位置
	 * @param isInbox 是否是收件箱
	 */
	private void removeOneMail(int mailIndex, boolean isInbox){
		if(isInbox){
			((MailAdapter)mInbox.getAdapter()).remove(mailIndex);
		}else{
			((MailAdapter)mOutbox.getAdapter()).remove(mailIndex);
		}
	}
	
	private void refreshFail(){
		mProgressHead.setVisibility(View.GONE);
		mRefresh.setText("刷新");
		mPopup.showToastWindow(Assistant.FAIL_POP, "获取数据失败");
	}
	
	/**
	 * 设置豆邮为以读
	 */
	private void setToRead(){
		mInbox.getAdapter().notifyDataSetChanged();
	}
	
    @Override
    protected void onResume() {
        MobclickAgent.onResume(this);
        super.onResume();    //Super Method super.onResume();
    }

    @Override
    protected void onPause() {
        MobclickAgent.onPause(this);
        super.onPause();    //Super Method super.onPause();
    }
}